package com.ruoyi.ocr.service.impl;

import com.baidu.aip.ocr.AipOcr;
import com.ruoyi.ocr.domain.DrivingLicenseOcrResult;
import com.ruoyi.ocr.domain.IdCardOcrResult;
import com.ruoyi.ocr.domain.OcrTask;
import com.ruoyi.ocr.mapper.DrivingLicenseOcrResultMapper;
import com.ruoyi.ocr.mapper.IdCardOcrResultMapper;
import com.ruoyi.ocr.mapper.OcrTaskMapper;
import com.ruoyi.ocr.service.OcrService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.HashMap;

/**
 * OCR识别服务实现类
 *
 * @author example
 */
@Service
public class OcrServiceImpl implements OcrService {

    // 百度OCR配置
    @Value("${baidu.ocr.appid}")
    private String appId;

    @Value("${baidu.ocr.apiKey}")
    private String apiKey;

    @Value("${baidu.ocr.secretKey}")
    private String secretKey;

    // 图片存储路径
    @Value("${ocr.image.path}")
    private String imagePath;

    private AipOcr client;

    private final OcrTaskMapper ocrTaskMapper;
    private final IdCardOcrResultMapper idCardOcrResultMapper;
    private final DrivingLicenseOcrResultMapper drivingLicenseOcrResultMapper;

    public OcrServiceImpl(OcrTaskMapper ocrTaskMapper,
                          IdCardOcrResultMapper idCardOcrResultMapper,
                          DrivingLicenseOcrResultMapper drivingLicenseOcrResultMapper) {
        this.ocrTaskMapper = ocrTaskMapper;
        this.idCardOcrResultMapper = idCardOcrResultMapper;
        this.drivingLicenseOcrResultMapper = drivingLicenseOcrResultMapper;
    }

    /**
     * 初始化百度OCR客户端
     */
    @PostConstruct
    public void init() {
        client = new AipOcr(appId, apiKey, secretKey);
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);
    }

    @Override
    public IdCardOcrResult idCardOcr(MultipartFile file) {
        // 1. 创建任务记录
        OcrTask task = createTask("idCard", file);
        IdCardOcrResult result = new IdCardOcrResult();
        result.setTaskId(task.getTaskId());

        try {
            // 2. 更新任务状态为处理中
            task.setStatus(1);
            ocrTaskMapper.updateTaskStatus(task);

            // 3. 调用百度OCR接口识别身份证
            byte[] imageData = file.getBytes();
            HashMap<String, String> options = new HashMap<>();
            options.put("detect_direction", "true");
            options.put("detect_risk", "false");

            // 正面识别，背面请使用Idcard.EVENT_BACK
            JSONObject res = client.idcard(imageData, "front", options);

            // 4. 解析识别结果
            JSONObject wordsResult = res.getJSONObject("words_result");

            result.setName(wordsResult.getJSONObject("姓名").getString("words"));
            result.setGender(wordsResult.getJSONObject("性别").getString("words"));
            result.setNation(wordsResult.getJSONObject("民族").getString("words"));
            result.setBirth(wordsResult.getJSONObject("出生").getString("words"));
            result.setAddress(wordsResult.getJSONObject("住址").getString("words"));
            result.setIdNumber(wordsResult.getJSONObject("公民身份号码").getString("words"));

            // 5. 保存识别结果
            idCardOcrResultMapper.insertIdCardResult(result);

            // 6. 更新任务状态为成功
            task.setStatus(2);
            ocrTaskMapper.updateTaskStatus(task);

        } catch (Exception e) {
            // 处理异常，更新任务状态为失败
            task.setStatus(3);
            task.setErrorMessage(e.getMessage());
            ocrTaskMapper.updateTaskStatus(task);
            throw new RuntimeException("身份证识别失败: " + e.getMessage());
        }

        return result;
    }

    @Override
    public DrivingLicenseOcrResult drivingLicenseOcr(MultipartFile file) {
        // 1. 创建任务记录
        OcrTask task = createTask("drivingLicense", file);
        DrivingLicenseOcrResult result = new DrivingLicenseOcrResult();
        result.setTaskId(task.getTaskId());

        try {
            // 2. 更新任务状态为处理中
            task.setStatus(1);
            ocrTaskMapper.updateTaskStatus(task);

            // 3. 调用百度OCR接口识别驾驶证
            byte[] imageData = file.getBytes();
            HashMap<String, String> options = new HashMap<>();

            JSONObject res = client.drivingLicense(imageData, options);

            // 4. 解析识别结果
            JSONObject wordsResult = res.getJSONObject("words_result");

            result.setName(wordsResult.getJSONObject("姓名").getString("words"));
            result.setGender(wordsResult.getJSONObject("性别").getString("words"));
            result.setNationality(wordsResult.getJSONObject("国籍").getString("words"));
            result.setAddress(wordsResult.getJSONObject("住址").getString("words"));
            result.setLicenseNumber(wordsResult.getJSONObject("证号").getString("words"));
            result.setDrivingType(wordsResult.getJSONObject("准驾车型").getString("words"));
            result.setDateOfIssue(wordsResult.getJSONObject("初次领证日期").getString("words"));
            result.setValidityPeriod(wordsResult.getJSONObject("有效期限").getString("words"));

            // 5. 保存识别结果
            drivingLicenseOcrResultMapper.insertDrivingLicenseResult(result);

            // 6. 更新任务状态为成功
            task.setStatus(2);
            ocrTaskMapper.updateTaskStatus(task);

        } catch (Exception e) {
            // 处理异常，更新任务状态为失败
            task.setStatus(3);
            task.setErrorMessage(e.getMessage());
            ocrTaskMapper.updateTaskStatus(task);
            throw new RuntimeException("驾驶证识别失败: " + e.getMessage());
        }

        return result;
    }

    @Override
    public IdCardOcrResult getIdCardResultByTaskId(Long taskId) {
        return idCardOcrResultMapper.selectByIdTaskId(taskId);
    }

    @Override
    public DrivingLicenseOcrResult getDrivingLicenseResultByTaskId(Long taskId) {
        return drivingLicenseOcrResultMapper.selectByTaskId(taskId);
    }

    /**
     * 创建OCR任务
     */
    private OcrTask createTask(String taskType, MultipartFile file) {
        try {
            // 保存文件到本地或云存储，这里简化处理
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            String filePath = imagePath + "/" + fileName;

            // TODO: 实现文件保存逻辑
            // file.transferTo(new File(filePath));

            OcrTask task = new OcrTask();
            task.setTaskType(taskType);
            task.setImagePath(filePath);
            task.setCreateTime(new Date());
            task.setStatus(0); // 初始状态：待处理

            ocrTaskMapper.insertOcrTask(task);
            return task;
        } catch (Exception e) {
            throw new RuntimeException("创建OCR任务失败: " + e.getMessage());
        }
    }
}
